"""
@name : book
@author : FanMY_71
@projectname: Selling-Idea
@Time: 2022/9/5-20:43
"""
from flask import Blueprint
from flask_restful import Api, Resource

from libs.handler import default_error_handler
from libs.response import generate_response
from model.tb_book import tb_book

booktop_bp = Blueprint("booktop", __name__, url_prefix="/v1")
api = Api(booktop_bp)


class BooktopView(Resource):
    def get(self):
        n = 0
        result = []
        # 降序排列
        booktop_infos = tb_book.query.order_by(tb_book.share_num.desc()).all()
        for booktop_info in booktop_infos:
            # 获取分享次数前十的书籍
            if n < 10:
                result.append(booktop_info)
                n += 1
        return generate_response(message="成功获取排行榜", data=[booktop_info.to_json() for booktop_info in result])


api.add_resource(BooktopView, "/booktops")
api.handle_error = default_error_handler
